package com.xblog.chatbox.vlmp.core.message;

import com.xblog.chatbox.vlmp.conversation.Conversation;
import com.xblog.chatbox.vlmp.conversation.ConversationPayloadFeedbacks;
import com.xblog.chatbox.vlmp.conversation.ConversationRequest;
import com.xblog.chatbox.vlmp.conversation.ConversationResponse;
import com.xiaowu.xblog.constant.UserContext;
import com.xiaowu.xblog.utils.SnowflakeIdWorker;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import reactor.core.publisher.Flux;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @description:
 * @author: xiaowu
 * @time: 2025/8/6 0:13
 */
@Component
public class VlmpAgentMessageBroker implements BeanPostProcessor {

    private final List<VlmpAgentMessageProvider> providers = new CopyOnWriteArrayList<>();

    private final Logger logger = LoggerFactory.getLogger(VlmpAgentMessageBroker.class);

    /**
     * topic主题匹配器
     */
    private final AntPathMatcher matcher = new AntPathMatcher();


    public Flux<ConversationResponse> subscribe(UserContext userContext, ConversationRequest request) {
        if (Objects.isNull(request.getRequestId())) {
            request.setRequestId(String.valueOf(SnowflakeIdWorker.getInstance().nextId()));
        }
        for (VlmpAgentMessageProvider provider : providers){
            if (this.isMatcher(provider.getTopic(),request.getTopic())){
                return provider.subscribe(userContext,request);
            }
        }
        logger.error("不支持的topic:{}",request.getTopic());
        return Flux.error(new UnsupportedOperationException("不支持的topic:" + request.getTopic()));
    }



    /**
     * 是否匹配
     *
     * @param pattern 匹配
     * @param topic   主题
     * @return 是否匹配
     */
    private boolean isMatcher(String pattern, String topic) {
        //如果订阅了则只发送订阅的信息
        return matcher.match(pattern, topic);
    }

    /**
     * 注册
     *
     * @param provider 提供者
     */
    public void register(VlmpAgentMessageProvider provider) {
        providers.add(provider);
        providers.sort(Comparator.comparingInt(VlmpAgentMessageProvider::getOrder));
    }

    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (bean instanceof VlmpAgentMessageProvider provider){
            register(provider);
        }
        return bean;
    }

    /**
     * 删除会话
     *
     * @param context 登录信息
     * @param conversation  会话信息
     */
    public void delete(UserContext context, Conversation conversation) {
        for (VlmpAgentMessageProvider provider : providers) {
            if (this.isMatcher(provider.getTopic(), conversation.getTopic())) {
                provider.delete(context, conversation);
            }
        }
    }

    public void rename(UserContext context, Conversation conversation) {
        for (VlmpAgentMessageProvider provider : providers) {
            if (this.isMatcher(provider.getTopic(), conversation.getTopic())) {
                provider.rename(context, conversation);
            }
        }
    }

    public void feedbacks(UserContext context, ConversationPayloadFeedbacks feedbacks) {
        for (VlmpAgentMessageProvider provider : providers) {
            if (this.isMatcher(provider.getTopic(), feedbacks.getTopic())) {
                provider.feedbacks(context, feedbacks);
            }
        }
    }
}
